from django.core.paginator import Paginator
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.urls import reverse

from goods.forms import GoodsVerify
from goods.models import GoodsCategory, Goods


def goods_category_detail(request, id):
    if request.method == 'GET':
        category = GoodsCategory.objects.filter(pk=id).first()
        types = GoodsCategory.CATEGORY_TYPE
        return render(request,'goods_category_detail.html',{'category':category,'types':types})
    if request.method == 'POST':
        img = request.FILES.get('category_front_image')
        if img:
            category = GoodsCategory.objects.filter(pk=id).first()
            category.category_front_image = img
            category.save()
            return HttpResponseRedirect(reverse('goods:goods_category_list'))
        else:
            error = '图片必填'
            return render(request,'goods_category_detail.html',{'error':error})


def goods_category_list(request):
    if request.method == 'GET':
        categorys = GoodsCategory.objects.all()
        types = GoodsCategory.CATEGORY_TYPE
        return render(request,'goods_category_list.html',{"categorys":categorys,'types':types})


def goods_desc(request, id):
    if request.method == 'GET':
        # TODO:返回商品对象，并刷新内容
        goods = Goods.objects.filter(pk=id).first()
        return render(request, 'goods_desc.html',{'goods':goods})

    if request.method == 'POST':
        # 获取编辑内容
        content = request.POST.get('content')
        # 修改商品
        goods = Goods.objects.filter(pk=id).first()
        goods.goods_desc = content
        goods.save()
        return HttpResponseRedirect(reverse('goods:goods_list',args=(1,)))


def goods_detail(request):
    if request.method == 'GET':
        #TODO:验证商品信息的完整性，数据的保存
        return render(request,'goods_detail.html')
    if request.method == 'POST':
        form = GoodsVerify(request.POST,request.FILES)  # 验证图片用，图片不在request.POST里面，可以验证多个
        if form.is_valid():
            # name = form.cleaned_data.get('name')
            # goods_sn = form.cleaned_data.get('goods_sn')
            # category = form.cleaned_data.get('category')
            # goods_nums = form.cleaned_data.get('goods_nums')
            # market_price = form.cleaned_data.get('market_price')
            # shop_price = form.cleaned_data.get('shop_price')
            # goods_brief = form.cleaned_data.get('goods_brief')
            # goods_front_image = img
            # Goods.objects.create(
            #     name=name,
            #     goods_sn=goods_sn,
            #     category_id=category, 注意外键，外键category是对象，而我们传参是数字，这个地方就是属性改成category_id
            #     goods_nums=goods_nums,
            #     market_price=market_price,
            #     shop_price=shop_price,
            #     goods_brief=goods_brief,
            #     goods_front_image = goods_front_image,
            #
            # )
            data = form.cleaned_data
            #category=对象,传的值是id,类型不匹配，要么将属性改成category_id接收id值，要么通过form表单验证，将外键单独验证，返回对象值
            Goods.objects.create(**data)
            return render(request,'goods_detail.html')
        else:
            return render(request, 'goods_detail.html',{'errors':form.errors})


def goods_list(request,id):
    if request.method == 'GET':
        # TODO:查询所有的商品信息，并在goods_list.html页面中解析
        #所有的商品数
        goods = Goods.objects.all()
        types = GoodsCategory.CATEGORY_TYPE
        # 按4个产品组成的页面数
        paginator = Paginator(goods,4)
        # 第id页的商品数
        goods = paginator.page(id)
        #第id页面下的第一个数字：
        num =int(id)*3-2
        #页面总数
        paginator_total = int(paginator.num_pages)
        range_pages = []

        if paginator_total - int(id) >= 3:
            for i in range(3):
                range_pages.append(str(int(id)+i))
        else:
            for i in range(paginator_total - int(id) + 1):
                range_pages.append(int(id)+i)
        return render(request,'goods_list.html',{'goods':goods,
                                                 'types':types,
                                                 'paginator':paginator,
                                                 'num':num,
                                                 'paginator_total':paginator_total,
                                                 'range_pages':range_pages,
                                                 })


def order_list(request):
    if request.method == 'GET':
        return render(request,'order_list.html')


def goods_alter(request,id):
    if request.method == 'GET':
        good = Goods.objects.filter(pk=id).first()
        return render(request,'goods_alter.html',{'good':good})
    if request.method == "POST":
        # img = request.FILES.get('goods_front_image')
        # name = request.POST.get('name')
        # goods_sn = request.POST.get('goods_sn')
        # category = request.POST.get('category')
        # goods_nums = request.POST.get('goods_nums')
        # market_price = request.POST.get('market_price')
        # shop_price = request.POST.get('shop_price')
        # goods_brief = request.POST.get('goods_brief')
        # if img:
        #     goods_front_image = img
        #     Goods.objects.filter(pk=id).update(
        #         name=name,
        #         goods_sn=goods_sn,
        #         category_id=category,
        #         goods_nums=goods_nums,
        #         market_price=market_price,
        #         shop_price=shop_price,
        #         goods_brief=goods_brief,
        #         goods_front_image=goods_front_image,
        #     )
        # else:
        #     Goods.objects.filter(pk=id).update(
        #         name=name,
        #         goods_sn=goods_sn,
        #         category_id=category,
        #         goods_nums=goods_nums,
        #         market_price=market_price,
        #         shop_price=shop_price,
        #         goods_brief=goods_brief,
        #     )
        #     return HttpResponseRedirect(reverse('goods:goods_list',1))
        form = GoodsVerify(request.POST,request.FILES)
        if form.is_valid():
            #验证成功
            data = form.cleaned_data
            # 把图片从data中删掉，
            # img表示更新商品时，选择了图片，则img为图片内容
            # 如果更新商品时，没有选择图片，则img为None
            img = data.pop('goods_front_image')
            # 更新除了图片的其他字段信息
            Goods.objects.filter(pk=id).update(**data)
            if img:
                # 更新图片的信息
                goods = Goods.objects.filter(pk=id).first()
                goods.goods_front_image = img
                goods.save()

            return HttpResponseRedirect(reverse('goods:goods_list', args=(1,)))
        else:
            # 修改验证失败
            good = Goods.objects.filter(pk=id).first()
            return render(request,'goods_detail.html',{'errors':form.errors,'good':'good'})
def goods_delete(request,id):
    if request.method == 'POST':
        # 删除商品数据，使用ajax
        Goods.objects.filter(pk=id).delete()
        return JsonResponse({'code':200,'msg':'请求成功'})